package com.xmhmyh.generalframework.framework.security.filter;

import com.alibaba.fastjson.JSONObject;
import com.xmhmyh.generalframework.common.utils.ServletUtils;
import com.xmhmyh.generalframework.framework.security.LoginUser;
import com.xmhmyh.generalframework.framework.security.TokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: 于丁
 * @DateTime: 2020/7/21 11:09 上午
 */
@Slf4j
@Component
public class JWTSecurityFilter extends OncePerRequestFilter {
    @Autowired
    private TokenService tokenService;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                                    FilterChain filterChain) throws ServletException, IOException {
        LoginUser loginUser = tokenService.getLoginUser(httpServletRequest);
        log.info("httpServletRequest：" + JSONObject.toJSONString(httpServletRequest.getHeaderNames()));
        log.info("getServletPath：" + JSONObject.toJSONString(httpServletRequest.getServletPath()));
        log.info("httpServletRequest2222：" + JSONObject.toJSONString( ServletUtils.getRequest().getHeaderNames()));
        if (loginUser != null) {
            log.info("token：" + loginUser.getToken());
            log.info("到达了这里：" + JSONObject.toJSONString(loginUser));
        }else{
            log.info("loginUser=null");
        }
        if (loginUser != null) {
            // 刷新token
            tokenService.verifyToken(loginUser);
            // 刷新权限信息
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}
